#!/bin/bash

# 设置颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 默认参数
INTERVAL=5      # 采样间隔（秒）
DURATION=60     # 监控时长（秒）
OUTPUT_FILE="memory_performance_report_$(date +%Y%m%d_%H%M%S).txt"
STATIC_INFO_FILE="memory_static_info_$(date +%Y%m%d_%H%M%S).txt"

# 帮助信息
show_help() {
    echo "用法: $0 [选项]"
    echo "选项:"
    echo "  -i, --interval <秒>   采样间隔（默认: 5秒）"
    echo "  -d, --duration <秒>   监控时长（默认: 60秒）"
    echo "  -o, --output <文件>   输出文件（默认: memory_performance_report_时间戳.txt）"
    echo "  -s, --static <文件>   静态信息文件（默认: memory_static_info_时间戳.txt）"
    echo "  -h, --help           显示此帮助信息"
    exit 0
}

# 解析命令行参数
while [[ $# -gt 0 ]]; do
    case $1 in
        -i|--interval)
            INTERVAL="$2"
            shift 2
            ;;
        -d|--duration)
            DURATION="$2"
            shift 2
            ;;
        -o|--output)
            OUTPUT_FILE="$2"
            shift 2
            ;;
        -s|--static)
            STATIC_INFO_FILE="$2"
            shift 2
            ;;
        -h|--help)
            show_help
            ;;
        *)
            echo "未知选项: $1"
            show_help
            ;;
    esac
done

# 收集内存静态信息
collect_memory_static_info() {
    echo "=== Linux 内存静态信息 ===" > "$STATIC_INFO_FILE"
    echo "收集时间: $(date)" >> "$STATIC_INFO_FILE"
    echo "----------------------------------------" >> "$STATIC_INFO_FILE"
    
    # 内存基本信息
    echo -e "\n1. 内存基本信息:" >> "$STATIC_INFO_FILE"
    echo "----------------------------------------" >> "$STATIC_INFO_FILE"
    echo "总内存:" >> "$STATIC_INFO_FILE"
    free -h | grep "Mem:" | awk '{print $2}' >> "$STATIC_INFO_FILE"
    echo "已用内存:" >> "$STATIC_INFO_FILE"
    free -h | grep "Mem:" | awk '{print $3}' >> "$STATIC_INFO_FILE"
    echo "可用内存:" >> "$STATIC_INFO_FILE"
    free -h | grep "Mem:" | awk '{print $7}' >> "$STATIC_INFO_FILE"
    
    # Swap信息
    echo -e "\n2. Swap信息:" >> "$STATIC_INFO_FILE"
    echo "----------------------------------------" >> "$STATIC_INFO_FILE"
    echo "总Swap空间:" >> "$STATIC_INFO_FILE"
    free -h | grep "Swap:" | awk '{print $2}' >> "$STATIC_INFO_FILE"
    echo "已用Swap:" >> "$STATIC_INFO_FILE"
    free -h | grep "Swap:" | awk '{print $3}' >> "$STATIC_INFO_FILE"
    
    # 内存详细统计
    echo -e "\n3. 内存详细统计:" >> "$STATIC_INFO_FILE"
    echo "----------------------------------------" >> "$STATIC_INFO_FILE"
    echo "详细内存信息:" >> "$STATIC_INFO_FILE"
    cat /proc/meminfo | grep -E "MemTotal|MemFree|MemAvailable|SwapTotal|SwapFree|Cached|Buffers|Slab|SReclaimable|SUnreclaim|KernelStack|PageTables|CommitLimit|Committed_AS" >> "$STATIC_INFO_FILE"
    
    # 内存相关系统限制
    echo -e "\n4. 内存相关系统限制:" >> "$STATIC_INFO_FILE"
    echo "----------------------------------------" >> "$STATIC_INFO_FILE"
    echo "系统内存参数:" >> "$STATIC_INFO_FILE"
    sysctl -a | grep -i "vm." | grep -E "swappiness|dirty_ratio|dirty_background_ratio|min_free_kbytes|overcommit_memory|vfs_cache_pressure" >> "$STATIC_INFO_FILE"
    
    # 内存高级特性
    echo -e "\n5. 内存高级特性:" >> "$STATIC_INFO_FILE"
    echo "----------------------------------------" >> "$STATIC_INFO_FILE"
    
    # 透明大页（THP）状态
    echo "透明大页(THP)状态:" >> "$STATIC_INFO_FILE"
    if [ -f "/sys/kernel/mm/transparent_hugepage/enabled" ]; then
        echo "  当前设置: $(cat /sys/kernel/mm/transparent_hugepage/enabled)" >> "$STATIC_INFO_FILE"
        echo "  说明: [always] = 始终启用, [madvise] = 按需启用, [never] = 禁用" >> "$STATIC_INFO_FILE"
    else
        echo "  透明大页信息不可用" >> "$STATIC_INFO_FILE"
    fi
    echo "" >> "$STATIC_INFO_FILE"
    
    # 内存压缩状态
    echo "内存压缩状态:" >> "$STATIC_INFO_FILE"
    if [ -d "/sys/block/zram0" ]; then
        echo "  zram: 已启用" >> "$STATIC_INFO_FILE"
        if [ -f "/sys/block/zram0/mm_stat" ]; then
            orig_data_size=$(cat /sys/block/zram0/mm_stat 2>/dev/null | awk '{print $1}')
            compr_data_size=$(cat /sys/block/zram0/mm_stat 2>/dev/null | awk '{print $2}')
            echo "  原始数据大小: $orig_data_size bytes" >> "$STATIC_INFO_FILE"
            echo "  压缩后大小: $compr_data_size bytes" >> "$STATIC_INFO_FILE"
        else
            echo "  无法读取zram统计信息" >> "$STATIC_INFO_FILE"
        fi
    else
        echo "  zram: 未启用" >> "$STATIC_INFO_FILE"
    fi
    
    if [ -f "/sys/module/zswap/parameters/enabled" ]; then
        zswap_enabled=$(cat /sys/module/zswap/parameters/enabled 2>/dev/null)
        if [ "$zswap_enabled" = "Y" ]; then
            echo "  zswap: 已启用" >> "$STATIC_INFO_FILE"
        else
            echo "  zswap: 未启用" >> "$STATIC_INFO_FILE"
        fi
    else
        echo "  zswap: 未启用" >> "$STATIC_INFO_FILE"
    fi
    echo "" >> "$STATIC_INFO_FILE"
    
    # 内存分配器信息
    echo "内存分配器信息:" >> "$STATIC_INFO_FILE"
    if command -v ldd &> /dev/null; then
        echo "  系统默认内存分配器:" >> "$STATIC_INFO_FILE"
        ldd_version=$(ldd --version | head -n 1)
        echo "  $ldd_version" >> "$STATIC_INFO_FILE"
        echo "  说明: 这是系统的C库实现，包含malloc等内存分配函数" >> "$STATIC_INFO_FILE"
    else
        echo "  无法确定系统默认内存分配器" >> "$STATIC_INFO_FILE"
    fi
    
    # 检查jemalloc
    if [ -f "/usr/lib/libjemalloc.so" ] || [ -f "/usr/lib64/libjemalloc.so" ]; then
        echo "  jemalloc: 可用" >> "$STATIC_INFO_FILE"
        echo "  说明: 高性能通用内存分配器，适用于多线程应用" >> "$STATIC_INFO_FILE"
    else
        echo "  jemalloc: 不可用" >> "$STATIC_INFO_FILE"
    fi
    
    # 检查tcmalloc
    if [ -f "/usr/lib/libtcmalloc.so" ] || [ -f "/usr/lib64/libtcmalloc.so" ]; then
        echo "  tcmalloc: 可用" >> "$STATIC_INFO_FILE"
        echo "  说明: Google开发的线程缓存内存分配器，针对并行程序优化" >> "$STATIC_INFO_FILE"
    else
        echo "  tcmalloc: 不可用" >> "$STATIC_INFO_FILE"
    fi
    
    echo -e "\n静态信息收集完成，已保存到: $STATIC_INFO_FILE"
}

# 创建输出文件
echo "=== Linux 内存性能监控报告 ===" > "$OUTPUT_FILE"
echo "开始时间: $(date)" >> "$OUTPUT_FILE"
echo "采样间隔: ${INTERVAL}秒" >> "$OUTPUT_FILE"
echo "监控时长: ${DURATION}秒" >> "$OUTPUT_FILE"
echo "----------------------------------------" >> "$OUTPUT_FILE"

# 收集内存静态信息
echo -e "${BLUE}正在收集内存静态信息...${NC}"
collect_memory_static_info

# 初始化计数器
count=0
total_samples=$((DURATION / INTERVAL))

# 创建临时文件存储数据
temp_memory_usage="/tmp/memory_usage_$$.tmp"
temp_swap_usage="/tmp/swap_usage_$$.tmp"
temp_processes="/tmp/processes_$$.tmp"
temp_page_faults="/tmp/page_faults_$$.tmp"
temp_oom="/tmp/oom_$$.tmp"
temp_cache_buffer="/tmp/cache_buffer_$$.tmp"
temp_swap_io="/tmp/swap_io_$$.tmp"

# 创建临时文件
touch "$temp_memory_usage" "$temp_swap_usage" "$temp_processes" "$temp_page_faults" "$temp_oom" "$temp_cache_buffer" "$temp_swap_io"

# 清理函数
cleanup() {
    # 检查是否已经清理过
    if [ -n "$CLEANUP_DONE" ]; then
        return
    fi
    
    rm -f "$temp_memory_usage" "$temp_swap_usage" "$temp_processes" "$temp_page_faults" "$temp_oom" "$temp_cache_buffer" "$temp_swap_io"
    echo -e "\n${GREEN}监控已完成，报告已保存到: $OUTPUT_FILE${NC}"
    echo -e "${GREEN}静态信息已保存到: $STATIC_INFO_FILE${NC}"
    
    # 标记清理已完成
    CLEANUP_DONE=1
    
    # 只有在非正常退出时才退出
    if [ -n "$1" ]; then
        exit 1
    fi
}

# 设置清理陷阱
trap 'cleanup 1' EXIT INT TERM

echo -e "${BLUE}开始监控内存性能...${NC}"
echo -e "采样间隔: ${INTERVAL}秒"
echo -e "监控时长: ${DURATION}秒"
echo -e "输出文件: $OUTPUT_FILE"
echo -e "按 Ctrl+C 可以提前结束监控\n"

# 主循环
while [ $count -lt $total_samples ]; do
    timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    
    # 收集内存使用情况
    mem_info=$(free -m | grep "Mem:")
    mem_total=$(echo "$mem_info" | awk '{print $2}')
    mem_used=$(echo "$mem_info" | awk '{print $3}')
    mem_free=$(echo "$mem_info" | awk '{print $4}')
    mem_available=$(echo "$mem_info" | awk '{print $7}')
    mem_usage=$(echo "scale=2; $mem_used * 100 / $mem_total" | bc)
    
    echo "$timestamp MEMORY_USAGE $mem_total $mem_used $mem_free $mem_available $mem_usage" >> "$temp_memory_usage"
    
    # 收集Swap使用情况
    swap_info=$(free -m | grep "Swap:")
    swap_total=$(echo "$swap_info" | awk '{print $2}')
    swap_used=$(echo "$swap_info" | awk '{print $3}')
    swap_free=$(echo "$swap_info" | awk '{print $4}')
    swap_usage=$(echo "scale=2; $swap_used * 100 / $swap_total" | bc)
    
    echo "$timestamp SWAP_USAGE $swap_total $swap_used $swap_free $swap_usage" >> "$temp_swap_usage"
    
    # 收集缓存和缓冲区信息
    cache=$(grep "Cached:" /proc/meminfo | awk '{print $2}')
    buffers=$(grep "Buffers:" /proc/meminfo | awk '{print $2}')
    slab=$(grep "Slab:" /proc/meminfo | awk '{print $2}')
    sreclaimable=$(grep "SReclaimable:" /proc/meminfo | awk '{print $2}')
    sunreclaim=$(grep "SUnreclaim:" /proc/meminfo | awk '{print $2}')
    
    echo "$timestamp CACHE_BUFFER $cache $buffers $slab $sreclaimable $sunreclaim" >> "$temp_cache_buffer"
    
    # 收集Swap I/O信息
    if [ -f "/proc/vmstat" ]; then
        # 获取当前的换入换出累计值
        pswpin=$(grep "pswpin" /proc/vmstat | awk '{print $2}')
        pswpout=$(grep "pswpout" /proc/vmstat | awk '{print $2}')
        
        # 第一次采样时，记录初始值
        if [ $count -eq 0 ]; then
            pswpin_prev=$pswpin
            pswpout_prev=$pswpout
        fi
        
        # 计算相对于上次采样的差值
        pswpin_diff=$((pswpin - pswpin_prev))
        pswpout_diff=$((pswpout - pswpout_prev))
        
        # 更新上次采样的值
        pswpin_prev=$pswpin
        pswpout_prev=$pswpout
        
        # 记录采样时的差值和绝对值
        echo "$timestamp SWAP_IO $pswpin_diff $pswpout_diff $pswpin $pswpout" >> "$temp_swap_io"
    else
        echo "$timestamp SWAP_IO 0 0 0 0" >> "$temp_swap_io"
    fi
    
    # 收集内存使用率最高的进程
    echo "$timestamp PROCESSES" > "$temp_processes.tmp"
    ps -eo pid,ppid,cmd,%mem,%cpu,rss,vsz --sort=-%mem | head -6 | tail -5 >> "$temp_processes.tmp"
    cat "$temp_processes.tmp" >> "$temp_processes"
    
    # 收集页面错误统计
    echo "$timestamp PAGE_FAULTS" > "$temp_page_faults.tmp"
    vmstat 1 1 | tail -n 1 >> "$temp_page_faults.tmp"
    cat "$temp_page_faults.tmp" >> "$temp_page_faults"
    
    # 收集OOM信息
    echo "$timestamp OOM" > "$temp_oom.tmp"
    dmesg | grep -i "out of memory" | tail -n 5 >> "$temp_oom.tmp"
    cat "$temp_oom.tmp" >> "$temp_oom"
    
    # 显示倒计时（每秒更新一次）
    remaining=$((DURATION - (count * INTERVAL)))
    for ((i=0; i<INTERVAL; i++)); do
        printf "\r${YELLOW}剩余时间: %d 秒${NC}" $((remaining - i))
        sleep 1
    done
    
    count=$((count + 1))
done

echo -e "\n\n${GREEN}正在生成报告...${NC}"

# 生成统计报告
echo -e "\n=== 内存使用率统计 ===" >> "$OUTPUT_FILE"
echo "时间戳                总内存(MB)  已用(MB)  可用(MB)  可用率(%)  使用率(%)" >> "$OUTPUT_FILE"
echo "------------------------------------------------" >> "$OUTPUT_FILE"
while read -r line; do
    if [[ "$line" == *"MEMORY_USAGE"* ]]; then
        timestamp=$(echo "$line" | cut -d' ' -f1,2)
        total=$(echo "$line" | cut -d' ' -f4)
        used=$(echo "$line" | cut -d' ' -f5)
        free=$(echo "$line" | cut -d' ' -f6)
        available=$(echo "$line" | cut -d' ' -f7)
        usage=$(echo "$line" | cut -d' ' -f8)
        awk -v ts="$timestamp" -v t="$total" -v u="$used" -v f="$free" -v a="$available" -v us="$usage" \
            'BEGIN {printf "%-20s %10d %10d %10d %10.2f%% %10.2f%%\n", ts, t, u, f, (a/t)*100, us}' >> "$OUTPUT_FILE"
    fi
done < "$temp_memory_usage"

echo -e "\n=== Swap使用率统计 ===" >> "$OUTPUT_FILE"
echo "时间戳                总Swap(MB)  已用(MB)  可用(MB)  使用率(%)" >> "$OUTPUT_FILE"
echo "------------------------------------------------" >> "$OUTPUT_FILE"
while read -r line; do
    if [[ "$line" == *"SWAP_USAGE"* ]]; then
        timestamp=$(echo "$line" | cut -d' ' -f1,2)
        total=$(echo "$line" | cut -d' ' -f4)
        used=$(echo "$line" | cut -d' ' -f5)
        free=$(echo "$line" | cut -d' ' -f6)
        usage=$(echo "$line" | cut -d' ' -f7)
        awk -v ts="$timestamp" -v t="$total" -v u="$used" -v f="$free" -v us="$usage" \
            'BEGIN {printf "%-20s %10d %10d %10d %10.2f%%\n", ts, t, u, f, us}' >> "$OUTPUT_FILE"
    fi
done < "$temp_swap_usage"

echo -e "\n=== 缓存和缓冲区统计 ===" >> "$OUTPUT_FILE"
echo "时间戳                缓存(KB)    缓冲区(KB)   Slab(KB)   可回收(KB)  不可回收(KB)" >> "$OUTPUT_FILE"
echo "------------------------------------------------" >> "$OUTPUT_FILE"
while read -r line; do
    if [[ "$line" == *"CACHE_BUFFER"* ]]; then
        timestamp=$(echo "$line" | cut -d' ' -f1,2)
        cache=$(echo "$line" | cut -d' ' -f4)
        buffers=$(echo "$line" | cut -d' ' -f5)
        slab=$(echo "$line" | cut -d' ' -f6)
        sreclaimable=$(echo "$line" | cut -d' ' -f7)
        sunreclaim=$(echo "$line" | cut -d' ' -f8)
        awk -v ts="$timestamp" -v c="$cache" -v b="$buffers" -v s="$slab" -v sr="$sreclaimable" -v su="$sunreclaim" \
            'BEGIN {printf "%-20s %10d %10d %10d %10d %10d\n", ts, c, b, s, sr, su}' >> "$OUTPUT_FILE"
    fi
done < "$temp_cache_buffer"

echo -e "\n=== Swap I/O统计 ===" >> "$OUTPUT_FILE"
echo "时间戳                换入增量    换出增量    累计换入    累计换出" >> "$OUTPUT_FILE"
echo "------------------------------------------------" >> "$OUTPUT_FILE"
while read -r line; do
    if [[ "$line" == *"SWAP_IO"* ]]; then
        timestamp=$(echo "$line" | cut -d' ' -f1,2)
        pswpin_diff=$(echo "$line" | cut -d' ' -f4)
        pswpout_diff=$(echo "$line" | cut -d' ' -f5)
        pswpin_total=$(echo "$line" | cut -d' ' -f6)
        pswpout_total=$(echo "$line" | cut -d' ' -f7)
        awk -v ts="$timestamp" -v pi_diff="$pswpin_diff" -v po_diff="$pswpout_diff" -v pi_total="$pswpin_total" -v po_total="$pswpout_total" \
            'BEGIN {printf "%-20s %10d %10d %10d %10d\n", ts, pi_diff, po_diff, pi_total, po_total}' >> "$OUTPUT_FILE"
    fi
done < "$temp_swap_io"

echo -e "\n=== 页面错误统计 ===" >> "$OUTPUT_FILE"
echo "时间戳                页面错误    页面回收    页面扫描    页面压缩" >> "$OUTPUT_FILE"
echo "------------------------------------------------" >> "$OUTPUT_FILE"
while read -r line; do
    if [[ "$line" == *"PAGE_FAULTS"* ]]; then
        timestamp=$(echo "$line" | cut -d' ' -f1,2)
        pgfault=$(echo "$line" | cut -d' ' -f4)
        pgpgout=$(echo "$line" | cut -d' ' -f5)
        pspgin=$(echo "$line" | cut -d' ' -f6)
        pspgout=$(echo "$line" | cut -d' ' -f7)
        awk -v ts="$timestamp" -v pf="$pgfault" -v pgo="$pgpgout" -v psi="$pspgin" -v pso="$pspgout" \
            'BEGIN {printf "%-20s %10d %10d %10d %10d\n", ts, pf, pgo, psi, pso}' >> "$OUTPUT_FILE"
    fi
done < "$temp_page_faults"

echo -e "\n=== 内存密集型进程统计 ===" >> "$OUTPUT_FILE"
current_timestamp=""
last_timestamp=""
while read -r line; do
    if [[ "$line" == *"PROCESSES"* ]]; then
        current_timestamp=$(echo "$line" | cut -d' ' -f1,2)
        
        # 如果不是第一次遇到时间戳，添加分割线
        if [[ -n "$last_timestamp" && "$current_timestamp" != "$last_timestamp" ]]; then
            echo "------------------------------------------------" >> "$OUTPUT_FILE"
        fi
        
        # 每次采样都添加表头
        echo "== 采样时间: $current_timestamp ==" >> "$OUTPUT_FILE"
        echo "------------------------------------------------" >> "$OUTPUT_FILE"
        echo "时间戳                PID    PPID    %MEM    %CPU    RSS(MB)    VIRT(MB)    COMMAND" >> "$OUTPUT_FILE"
        echo "------------------------------------------------" >> "$OUTPUT_FILE"
        
        last_timestamp="$current_timestamp"
    elif [[ -n "$current_timestamp" ]]; then
        pid=$(echo "$line" | awk '{print $1}')
        ppid=$(echo "$line" | awk '{print $2}')
        cmd=$(echo "$line" | awk '{print $3}')
        mem=$(echo "$line" | awk '{print $4}')
        cpu=$(echo "$line" | awk '{print $5}')
        rss=$(echo "$line" | awk '{print $6}')
        vsz=$(echo "$line" | awk '{print $7}')
        awk -v ts="$current_timestamp" -v p="$pid" -v pp="$ppid" -v m="$mem" -v c="$cpu" -v r="$rss" -v v="$vsz" -v cmd="$cmd" \
            'BEGIN {printf "%-20s %6s %6s %7.2f%% %7.2f%% %10d %10d %s\n", ts, p, pp, m, c, r, v, cmd}' >> "$OUTPUT_FILE"
    fi
done < "$temp_processes"

echo -e "\n=== OOM (内存不足) 信息 ===" >> "$OUTPUT_FILE"
echo "时间戳                事件信息" >> "$OUTPUT_FILE"
echo "------------------------------------------------" >> "$OUTPUT_FILE"
current_timestamp=""
while read -r line; do
    if [[ "$line" == *"OOM"* ]]; then
        current_timestamp=$(echo "$line" | cut -d' ' -f1,2)
        echo "== 采样时间: $current_timestamp ==" >> "$OUTPUT_FILE"
        echo "------------------------------------------------" >> "$OUTPUT_FILE"
    elif [[ -n "$current_timestamp" && "$line" != *"OOM"* ]]; then
        echo "$current_timestamp $line" >> "$OUTPUT_FILE"
    fi
done < "$temp_oom"

# 计算平均值
echo -e "\n=== 统计摘要 ===" >> "$OUTPUT_FILE"
echo "------------------------------------------------" >> "$OUTPUT_FILE"

# 内存使用率平均值
mem_avg=$(awk '/MEMORY_USAGE/ {sum+=$8; count++} END {print (count>0) ? sum/count : 0}' "$temp_memory_usage")
mem_used_avg=$(awk '/MEMORY_USAGE/ {sum+=$5; count++} END {print (count>0) ? sum/count : 0}' "$temp_memory_usage")
mem_free_avg=$(awk '/MEMORY_USAGE/ {sum+=$6; count++} END {print (count>0) ? sum/count : 0}' "$temp_memory_usage")
mem_available_avg=$(awk '/MEMORY_USAGE/ {sum+=$7; count++} END {print (count>0) ? sum/count : 0}' "$temp_memory_usage")

echo "内存使用率平均值: ${mem_avg}% (已用: ${mem_used_avg}MB, 可用: ${mem_free_avg}MB, 可用率: $(echo "scale=2; ${mem_available_avg} * 100 / $(awk '/MEMORY_USAGE/ {print $4; exit}' "$temp_memory_usage")" | bc)%)" >> "$OUTPUT_FILE"

# Swap使用率平均值
swap_avg=$(awk '/SWAP_USAGE/ {sum+=$7; count++} END {print (count>0) ? sum/count : 0}' "$temp_swap_usage")
swap_used_avg=$(awk '/SWAP_USAGE/ {sum+=$5; count++} END {print (count>0) ? sum/count : 0}' "$temp_swap_usage")
swap_free_avg=$(awk '/SWAP_USAGE/ {sum+=$6; count++} END {print (count>0) ? sum/count : 0}' "$temp_swap_usage")

echo "Swap使用率平均值: ${swap_avg}% (已用: ${swap_used_avg}MB, 可用: ${swap_free_avg}MB)" >> "$OUTPUT_FILE"

# 缓存和缓冲区平均值
cache_avg=$(awk '/CACHE_BUFFER/ {sum+=$4; count++} END {print (count>0) ? sum/count : 0}' "$temp_cache_buffer")
buffers_avg=$(awk '/CACHE_BUFFER/ {sum+=$5; count++} END {print (count>0) ? sum/count : 0}' "$temp_cache_buffer")
slab_avg=$(awk '/CACHE_BUFFER/ {sum+=$6; count++} END {print (count>0) ? sum/count : 0}' "$temp_cache_buffer")
sreclaimable_avg=$(awk '/CACHE_BUFFER/ {sum+=$7; count++} END {print (count>0) ? sum/count : 0}' "$temp_cache_buffer")
sunreclaim_avg=$(awk '/CACHE_BUFFER/ {sum+=$8; count++} END {print (count>0) ? sum/count : 0}' "$temp_cache_buffer")

echo "缓存和缓冲区平均值: 缓存=${cache_avg}KB, 缓冲区=${buffers_avg}KB, Slab=${slab_avg}KB (可回收=${sreclaimable_avg}KB, 不可回收=${sunreclaim_avg}KB)" >> "$OUTPUT_FILE"

# Swap I/O平均值
pswpin_diff_avg=$(awk '/SWAP_IO/ {sum+=$4; count++} END {print (count>0) ? sum/count : 0}' "$temp_swap_io")
pswpout_diff_avg=$(awk '/SWAP_IO/ {sum+=$5; count++} END {print (count>0) ? sum/count : 0}' "$temp_swap_io")

echo "Swap I/O平均值: 每次采样换入增量=${pswpin_diff_avg}页, 每次采样换出增量=${pswpout_diff_avg}页" >> "$OUTPUT_FILE"

# 页面错误平均值
pgfault_avg=$(awk '/PAGE_FAULTS/ {sum+=$4; count++} END {print (count>0) ? sum/count : 0}' "$temp_page_faults")
pgpgout_avg=$(awk '/PAGE_FAULTS/ {sum+=$5; count++} END {print (count>0) ? sum/count : 0}' "$temp_page_faults")
pspgin_avg=$(awk '/PAGE_FAULTS/ {sum+=$6; count++} END {print (count>0) ? sum/count : 0}' "$temp_page_faults")
pspgout_avg=$(awk '/PAGE_FAULTS/ {sum+=$7; count++} END {print (count>0) ? sum/count : 0}' "$temp_page_faults")

echo "平均页面错误: ${pgfault_avg} (页面回收: ${pgpgout_avg}, 页面扫描: ${pspgin_avg}, 页面压缩: ${pspgout_avg})" >> "$OUTPUT_FILE"

echo -e "\n结束时间: $(date)" >> "$OUTPUT_FILE"
echo "----------------------------------------" >> "$OUTPUT_FILE"

# 正常完成，调用cleanup但不退出
cleanup 

